package com.ycyoes.demos.netty.demo.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import org.bouncycastle.util.Pack;

import static com.ycyoes.demos.netty.demo.protocol.LoginRequestPacket.getRequestType;
import static com.ycyoes.demos.netty.demo.protocol.Serializer.getSerializer;

public class PacketCodeC {
    private PacketCodeC() {}

    public static PacketCodeC INSTANCE = null;

    public static PacketCodeC getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new PacketCodeC();
        }
        return INSTANCE;
    }
    private static final int MAGIC_NUMBER = 0x12345678;

    public Packet decode(ByteBuf byteBuf) {
        //跳过魔数
        byteBuf.skipBytes(4);
        //跳过版本号
        byteBuf.skipBytes(1);
        //序列化算法标识
        byte serializeAlgorithm = byteBuf.readByte();
        //指令
        byte command = byteBuf.readByte();
        //数据包长度
        int length = byteBuf.readInt();

        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);

        Class<? extends Packet> requestType = getRequestType(command);
        Serializer serializer = getSerializer(serializeAlgorithm);

        if (requestType != null && serializer != null) {
            return serializer.deserialize(requestType, bytes);
        }
        return null;
    }
    public static ByteBuf encode(ByteBufAllocator alloc, Packet packet) {
        //1. 创建ByteBuf对象
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.ioBuffer();
        //2. 序列化Java对象
        byte[] bytes = Serializer.DEFAULT.serialize(packet);
        //3. 实际编码过程
        byteBuf.writeInt(MAGIC_NUMBER);
        byteBuf.writeByte(packet.getVersion());
        byteBuf.writeByte(Serializer.DEFAULT.getSerializerAlgorithm());
        byteBuf.writeByte(packet.getCommand());
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);

        return byteBuf;
    }
}
